package com.douyinkan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.douyinkan.entity.SystemConfig;
import com.douyinkan.mapper.SystemConfigMapper;
import com.douyinkan.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SystemConfigServiceImpl implements SystemConfigService {

    @Autowired
    private SystemConfigMapper systemConfigMapper;

    @Override
    public SystemConfig getConfigByKey(String key) {
        QueryWrapper<SystemConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", key);
        return systemConfigMapper.selectOne(wrapper);
    }

    @Override
    public SystemConfig saveConfig(String key, String value, String description) {
        SystemConfig config = new SystemConfig(key, value, description);
        systemConfigMapper.insert(config);
        return config;
    }

    @Override
    public SystemConfig updateConfig(String key, String value) {
        QueryWrapper<SystemConfig> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", key);
        SystemConfig existingConfig = systemConfigMapper.selectOne(wrapper);
        if (existingConfig != null) {
            existingConfig.setConfigValue(value);
            systemConfigMapper.updateById(existingConfig);
            return existingConfig;
        } else {
            return saveConfig(key, value, "Auto created");
        }
    }
}